package com.lt.test.consumer.web.shiro;

import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.annotation.Reference;
import com.lt.test.api.UserService;
import com.lt.test.common.constant.ShiroMd5HashConstant;
import com.lt.test.common.exception.CustomException;
import com.lt.test.entity.DTO.ActiveUser;
import com.lt.test.entity.DTO.CustomUser;
import com.lt.test.entity.DTO.MenuDTO;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;


public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Override
    public String getName() {
        return "customRealm";
    }

    // 支持什么类型的token
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //身份信息
        ActiveUser activeUser = (ActiveUser) principalCollection.getPrimaryPrincipal();
        //用户roleId
        String roleId = activeUser.getRoleId();
        //获取用户权限
        List<String> permissions = null;
        try {
            permissions = userService.findPermissionStrList(roleId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //构建shiro授权信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for(String sysPermission :  permissions){
            simpleAuthorizationInfo.addStringPermission(sysPermission);
        }
        return simpleAuthorizationInfo;
}

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 从token中 获取用户身份信息
        String username = (String) authenticationToken.getPrincipal();
        // 拿username从数据库中查询
        // ....
        // 如果查询不到则返回null
        CustomUser customUser = null;

        /**--------自动登录的特殊处理---*/
        boolean isAutoLogin = false;
        if (username.startsWith("0")) {
            isAutoLogin = true;
            username = username.substring(1);
        }
        /**--------------------------*/
        try {
            customUser = userService.findCustomByPhone(username);
        } catch (Exception e) {
            e.printStackTrace();

        }
        if (customUser == null) {
            return null;
        }
        List<MenuDTO> menus = new ArrayList<>();
        try {
            menus = userService.findUserMenusByRoleId(customUser.getRoleId());
        } catch (CustomException e) {
            e.printStackTrace();
        }
        ActiveUser activeUser = new ActiveUser();
        activeUser.setUserId(customUser.getId());
        activeUser.setUsername(customUser.getUsername());
        activeUser.setPhone(customUser.getPhone());
        activeUser.setRoleId(customUser.getRoleId());
        activeUser.setChannelName(customUser.getChannelName());
        activeUser.setEmpName(customUser.getEmpName());
        activeUser.setRealChannelName(customUser.getRealChannelName());
        activeUser.setQuXianName(customUser.getQuXianName());
        activeUser.setClouderUser(customUser.getClouderUser());
        activeUser.setRoleNo(customUser.getRoleNo());
        activeUser.setZoneCode(customUser.getZoneCode());
        activeUser.setMenus(menus);
        activeUser.setClouderpUser(customUser.getClouderpUser());
        // 获取从数据库查询出来的用户密码
        String password = customUser.getPassword();

        if (isAutoLogin) {
            password = "f8bb98e859cc233422b6f455912de922";
        }

        // 返回认证信息由父类AuthenticatingRealm进行认证
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                activeUser, password, ByteSource.Util.bytes(ShiroMd5HashConstant.SALT), getName());

        return simpleAuthenticationInfo;

    }

    //清除缓存
  /*  public void clearCached() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }*/


}
